package com.duan.blog.controller;

import com.duan.blog.common.RespUtil;
import com.duan.blog.common.StringUtil;
import com.duan.blog.config.JWTUtil;
import com.duan.blog.constants.CodeEnum;
import com.duan.blog.model.vo.NamePasswordVo;
import com.duan.blog.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.Optional;

/**
 * @author: dcf
 * @description： 登录
 * @dateTime: 2021-12-21 18:17
 **/
@RestController
public class LoginController {
    @Autowired
    UserService userService;

    @PostMapping(value = "/login")
    public RespUtil login(@RequestParam("userName") String userName,
                          @RequestParam("password") String password,
                          HttpServletResponse httpServletResponse){
        NamePasswordVo namePasswordVo = Optional.ofNullable(userService.selectNameAndPasswordByName(userName)).orElse(new NamePasswordVo());
        if(!StringUtil.isEmpty(namePasswordVo.getUserPassword()) && namePasswordVo.getUserPassword().equals(password)){
            String token = JWTUtil.createToken(userName);
            httpServletResponse.setHeader("token", token);
            return RespUtil.success(token);
        }else{
            return RespUtil.fail(CodeEnum.USER_INVALID_ERROR);
        }

    }

}
